package edu.imu.question.service.impl;

import edu.imu.question.config.constans.UserStatusEnum;
import edu.imu.question.controller.form.LoginForm;
import edu.imu.question.entity.ResponseResult;
import edu.imu.question.entity.User;
import edu.imu.question.mapper.UserMapper;
import edu.imu.question.service.LoginLogService;
import edu.imu.question.service.LoginLogoutService;
import edu.imu.question.util.EncryptUtil;
import edu.imu.question.util.HttpServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

import static edu.imu.question.config.GlobalConstant.SESSION_KEY_CURR_USER;
import static edu.imu.question.config.GlobalConstant.SESSION_KEY_LOGIN_ERR_COUNT;

@Service
public class LoginLogoutServiceImpl implements LoginLogoutService {
    private final UserMapper userMapper;
    private final LoginLogService loginLogService;

    @Autowired
    public LoginLogoutServiceImpl(UserMapper userMapper,LoginLogService loginLogService) {
        this.userMapper = userMapper;
        this.loginLogService = loginLogService;
    }

    @Override
    public ResponseResult login(LoginForm loginForm) {
        final List<User> users = userMapper.findByUsername(loginForm.getUsername());
        final HttpSession session = HttpServletUtil.getSession();
        if(users == null || users.isEmpty()){
            int count = incrementLoginErrorCount(session);
            return ResponseResult.error("用户名或密码错误",count);
        }
        User user = users.get(0);
        final String inputPass = EncryptUtil.encryptPassword(loginForm.getPassword(), user.getPasswordSalt());
        if(inputPass != null && inputPass.equals(user.getPassword())){
            //如果用户被锁定
            if(user.getStatus() == UserStatusEnum.LOCKED.getStatus())
                return ResponseResult.error("用户已被锁定，请联系客服！",null);
            session.setAttribute(SESSION_KEY_CURR_USER,user);
            session.removeAttribute(SESSION_KEY_LOGIN_ERR_COUNT); //登录成功清楚登录错误计数
            loginLogService.addLoginLog(user.getId());
            return ResponseResult.ok("登录成功！",null);
        }
        int count = incrementLoginErrorCount(session);
        return ResponseResult.error("用户名或密码错误",count);
    }

    private int incrementLoginErrorCount(HttpSession session){
        Integer count = (Integer) (session.getAttribute(SESSION_KEY_LOGIN_ERR_COUNT)==null?0:
                session.getAttribute(SESSION_KEY_LOGIN_ERR_COUNT));
        session.setAttribute(SESSION_KEY_LOGIN_ERR_COUNT,count+1);
        return count+1;
    }
}
